package dimensional.traveler.server.services.servlets;

import java.util.regex.Pattern;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.inject.Inject;

import dimensional.traveler.client.services.LoginService;
import dimensional.traveler.server.model.User;
import dimensional.traveler.server.persistence.UserRepository;
import dimensional.traveler.shared.LoginInfo;

public class LoginServiceImpl extends RemoteServiceServlet implements LoginService {

	private static final long serialVersionUID = 6238220808508004233L;

	private static Pattern validCharacters = Pattern.compile("^[A-Za-z0-9]+$");

	@Inject
	UserRepository userRepository;

	@Override
	public LoginInfo login(String username, String password) {
		boolean existingUser = userExists(username);
		if (existingUser){
			return new LoginInfo();
		}
		else{
			LoginInfo loginInfo = new LoginInfo( "User does not exist" );
			return loginInfo;
		}
	}

	@Override
	public LoginInfo createUser(String userName, String password) {
		if (!containsOnlyValidCharacters(userName)){
			LoginInfo loginInfo = new LoginInfo("User name should only contain alphanumeric characters");
			return loginInfo;
		}
		if (userExists(userName)){
			LoginInfo loginInfo = new LoginInfo("User already exists");
			return loginInfo;
		}
		User user = new User(userName, password);
		userRepository.addUser(user);
		return new LoginInfo();
	}
	
	private boolean userExists(String username) {
		User user = userRepository.getUserByUserName(username);
		boolean existingUser = user != null;
		return existingUser;
	}    
	
	private boolean containsOnlyValidCharacters(String s) {
        return validCharacters.matcher(s).matches();
    }
	
	@Override
	public void logout(String username) {
		// TODO Auto-generated method stub

	}

}
